package me.zhengjie.modules.zhihu.visit.callable;

import cn.hutool.core.lang.Console;
import me.zhengjie.config.ApplicationContextProvider;
import me.zhengjie.modules.zhihu.common.QuesiontUtils;
import me.zhengjie.modules.zhihu.question.domain.ZhihuQuestion;
import me.zhengjie.modules.zhihu.visit.domain.ZhQuestionVisit;
import me.zhengjie.modules.zhihu.visit.service.ZhQuestionVisitService;

import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

public class VisitNumCallable implements Callable<List<ZhQuestionVisit>> {
    String BASE_URL = "https://www.zhihu.com/question/";
    private List<String> ids;
    private AtomicInteger count;
    //List<String> range;
    static ZhQuestionVisitService zhQuestionVisitService = ApplicationContextProvider.getBean(ZhQuestionVisitService.class);
    static DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public VisitNumCallable(List<String> ids, AtomicInteger count) {
        this.ids = ids;
        this.count = count;
    }

    public List<ZhQuestionVisit> call() throws Exception {
        ArrayList visits = new ArrayList();

        try {
            Iterator var2 = this.ids.iterator();
            Timestamp timestamp = new Timestamp(new Date().getTime());
            while(var2.hasNext()) {
                String id = (String)var2.next();
                //String visitNum = QuesiontUtils.getQuestionVisitNum(this.BASE_URL + id,0,range);
                String visitNum = QuesiontUtils.getQuestionVisitNum(this.BASE_URL + id);
                ZhQuestionVisit visit = new ZhQuestionVisit();
                visit.setId(id);
                visit.setVisitDate(timestamp);
                visit.setVisitNum(Integer.parseInt(visitNum));
                zhQuestionVisitService.create(visit);
                Console.log("当前线程：{},成功转化第{}条", new Object[]{Thread.currentThread().getName(), this.count.addAndGet(1)});
                visits.add(visit);
                Thread.sleep(10000L);
            }
        } catch (NumberFormatException var8) {
            var8.printStackTrace();
            Console.error("当前线程：{},转化失败第{}条", new Object[]{Thread.currentThread().getName(), this.count.addAndGet(1)});
        }
        return visits;
    }



}
